package com.example.forum.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.example.forum.commons.authrization.TokenManager;
import com.example.forum.commons.tools.StringUtil;
import com.example.forum.commons.tools.Transfer.DataTransfer;
import com.example.forum.entity.TPermissions;
import com.example.forum.service.ITPermissionsService;
import com.example.forum.vo.JsonResult;
import com.example.forum.vo.PermissionModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * <p>
 * 权限控制器
 * </p>
 *
 * @author why
 * @since 2019-10-30
 */

@RestController
@Api(tags = "权限控制层")
@RequestMapping("/Permission")
public class TPermissionsController extends BaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(TPermissionsController.class);

    @Autowired
    private ITPermissionsService permissionsService;
    @Autowired
    DataTransfer dataTransfer;
    @Autowired
    private TokenManager tokenManager;


    @ApiOperation(value = "添加权限")
    @RequestMapping(value = "/create", method = {RequestMethod.POST})
    public JsonResult create(@Valid @RequestBody @ApiParam(name = "权限对象", value = "传入json格式", required = true) PermissionModel permissionModel) {

        TPermissions permission = permissionsService.getOne(new QueryWrapper<TPermissions>()
                .eq("targetName", permissionModel.getTargetname()));

        if (permission != null) {
            return new JsonResult(HttpStatus.BAD_REQUEST, "权限值已存在", null);
        }

        TPermissions pdt = new TPermissions();
        var dto = (TPermissions) dataTransfer.getObjectFromObject(pdt, permissionModel);
        dto.setCreatoruserid(currentUserId());
        permissionsService.save(dto);

        TPermissions permissionR = permissionsService.getOne(new QueryWrapper<TPermissions>()
                .eq("targetName", permissionModel.getTargetname()));

        return new JsonResult(HttpStatus.OK, "添加成功", permissionR.getId());
    }


    @ApiOperation(value = "更新权限")
    @RequestMapping(value = "/update", method = {RequestMethod.POST})
    public JsonResult update(
          @Valid  @RequestBody @ApiParam(name = "权限对象", value = "传入json格式", required = true) PermissionModel permissionModel) {

        TPermissions permission = permissionsService.getOne(new QueryWrapper<TPermissions>()
                .eq("targetName", permissionModel.getTargetname())
                .ne("id",permissionModel.getPermissionId())
        );

        if (permission != null) {
            return new JsonResult(HttpStatus.BAD_REQUEST, "权限值已存在", null);
        }

        var permissiondto = permissionsService.getById(permissionModel.getPermissionId());
        permissiondto = (TPermissions) dataTransfer.getObjectFromObject(permissiondto, permissionModel);
        permissionsService.updateById(permissiondto);

        return new JsonResult(HttpStatus.OK, "更新成功", null);
    }


    @ApiOperation(value = "删除权限")
    @RequestMapping(value = "/delete", method = {RequestMethod.POST})
    public JsonResult delete(String permissionId) {
        LOGGER.info("删除权限");
        var pdto = permissionsService.getById(permissionId);
        if (pdto == null) {
            return new JsonResult(HttpStatus.NOT_FOUND, "该权限不存在", null);
        } else {
            pdto.setIsdeleted(true);
            pdto.setDeleteruserid(currentUserId());
            permissionsService.updateById(pdto);
            return new JsonResult(HttpStatus.OK, "删除成功", null);
        }
    }


    @ApiOperation(value = "检查权限名是否重复（true:已存在 false:不存在）")
    @RequestMapping(value = "/checkPermissionNameDup", method = {RequestMethod.POST})
    public JsonResult checkPermissionNameDup(String permissionName) {
        if (StringUtil.isEmpty(permissionName)) {
            return new JsonResult(HttpStatus.NOT_FOUND, "权限名不能为空", null);
        }
        var permission = permissionsService.getOne(new QueryWrapper<TPermissions>()
                .eq("targetName", permissionName));
        if (permission != null) {
            return new JsonResult(HttpStatus.OK, "成功 ", true);
        }
        return new JsonResult(HttpStatus.OK, "成功 ", false);
    }


    @ApiOperation(value = " 根据Id获取权限。200获取成功")
    @RequestMapping(value = "/getInfo", method = {RequestMethod.GET})
    public JsonResult getInfo(String permissionId) {
        var result = permissionsService.getById(permissionId);
        return new JsonResult(HttpStatus.OK, "成功 ", result);
    }


    @ApiOperation(value = " 分页获取权限列表。200获取成功")
    @RequestMapping(value = "/getList", method = {RequestMethod.GET})
    public JsonResult getList(String displayName, String permissionType, Integer pageIndex, int pageSize) {
        Page<TPermissions> page = new Page(pageIndex,pageSize);

        var result = permissionsService.page(page, new QueryWrapper<TPermissions>().
                like(StringUtil.isNotEmpty(displayName),"displayName", displayName)
                .eq(StringUtil.isNotEmpty(permissionType),"permissionType", permissionType)
                .eq("isdeleted", 0)
                .orderByDesc("creationtime"));;
        return new JsonResult(HttpStatus.OK, "成功 ", result);
    }


    @ApiOperation(value = "  获取所有普通权限")
    @RequestMapping(value = "/getPermissionAll", method = {RequestMethod.GET})
    public JsonResult getPermissionAll() {
        var result = permissionsService.list(new QueryWrapper<TPermissions>().eq("permissionType", 2));
        return new JsonResult(HttpStatus.OK, "成功 ", result);
    }
}


